package com.cucn.ingmall.ware.config;

import com.cucn.common.constant.ware.WareConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author KouChaoJie
 * @since: 2022/1/18 10:48
 */
@Configuration
@Slf4j
public class MyRabbitMqConfig {

    /**
     * 序列化json消息
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * stock-event-exchange
     * 交换机
     */
    @Bean
    public Exchange stockEventExchange() {
        return new TopicExchange(WareConstant.STOCK_EVENT_EXCHANGE, true, false);
    }

    /**
     * stock.release.stock.queue
     * 接收死信队列后传出的消息
     */
    @Bean
    public Queue stockReleaseStockQueue() {
        return new Queue(WareConstant.STOCK_RELEASE_STOCK_QUEUE, true, false, false);
    }

    /**
     * stock.delay.queue
     * 延时队列
     *
     * @return
     */
    @Bean
    public Queue stockDelayQueue() {
        //配置消息的过期时间及死信路由和死信交换机
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", WareConstant.STOCK_EVENT_EXCHANGE);
        arguments.put("x-dead-letter-routing-key", WareConstant.X_DEAD_LETTER_ROUTING_KEY);
        arguments.put("x-message-ttl", WareConstant.X_MESSAGE_TTL);

        return new Queue(WareConstant.STOCK_DELAY_QUEUE, true, false, false, arguments);
    }

    /**
     * 延时队列的绑定关系
     */
    @Bean
    public Binding stockLockedBinding() {
        return new Binding(WareConstant.STOCK_DELAY_QUEUE,
                Binding.DestinationType.QUEUE,
                WareConstant.STOCK_EVENT_EXCHANGE,
                WareConstant.STOCK_LOCKED_BINDING_ROUTINGKEY,
                null
        );
    }

    /**
     * release队列的绑定关系
     */
    @Bean
    public Binding stockReleaseBinding() {
        return new Binding(WareConstant.STOCK_RELEASE_STOCK_QUEUE,
                Binding.DestinationType.QUEUE,
                WareConstant.STOCK_EVENT_EXCHANGE,
                WareConstant.STOCK_RELEASE_BINDING_ROUTINGKEY,
                null
        );
    }
}
